package com.time.company.components.task;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseFragment;
import com.time.company.base.BaseRecAdapter;
import com.time.company.common.event.BaseEvent;
import com.time.company.components.MainActivity;
import com.time.company.components.WebDetailActivity;
import com.time.company.components.compose.TimeMapActivity;
import com.time.company.components.discovery.DiscoveryFragment;
import com.time.company.components.popup.WelBackPW;
import com.time.company.servermodel.AppBanner;
import com.time.company.servermodel.task.ClockOn;
import com.time.company.servermodel.task.TaskData;
import com.time.company.utils.TimeUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.utils.string.Constant;
import com.time.company.views.WrapHeightRecyclerView;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by Bing on 2017/10/25.
 * E-mail is tx16bing@163.com
 */

public class TaskFragment extends BaseFragment implements View.OnClickListener,
        AMapLocationListener {

    private static final int TIME_MAP_REQUEST_CODE = 11;

    private TaskRequest taskRequest;

    // Views
    private LinearLayout llParent;
    private ImageView ivMsg;
    private TextView tvTimeLev, tvVipLev, tvTimeTotalHour, tvTimeTotalMin, tvTimeTotalSecond,
            tvTimeCoin, tvNowTime, tvTodayServiceTime,
            tvTimeMarker, tvUserManage, tvRanking, tvClockIn, tvHonor;
    private ImageView ivLayer;
    //    private Banner mBanner;
    private LinearLayout llClockIn, llVolunteer;
    private WrapHeightRecyclerView rvBanner, rvClockIn, rvVolunteer;
    private TextView tvLookMore;

    private TaskData mTaskData;
    private ArrayList<String> bannerImages = new ArrayList<>();

    private BannerAdapter mBannerAdapter;
    private ClockAdapter mClockAdapter;
    private RecentAdapter mRecentAdapter;

    // AMap
    private AMapLocationClient locationRequest;
    private AMapLocation aMapLocation;
    // 当前定位
    private String curLocation;

    // 当前位置
    private int curPosition;

    // 窗口背景属性
    private WindowManager.LayoutParams attributes;
    private WelBackPW welBackPW;

    // 现在时间的倒计时
    private long nowTimeCountDown;
    // 累积公益时间的计时器
    private long todayServiceTime;

    @Override
    public void initContentView(View contentView) {
        EventBus.getDefault().register(this);
        mTaskData = new TaskData();
        assignViews();
        initRv();
        andPermission();
        bindRegAward();
        initRequest();
    }

    private void assignViews() {
        llParent = findView(R.id.ll_task_fragment_parent);
        ivMsg = findView(R.id.iv_task_message);
        tvTimeLev = findView(R.id.tv_task_time_lev);
        tvVipLev = findView(R.id.tv_task_vip_lev);
        ivLayer = findView(R.id.iv_task_vip_layer);
        tvTimeTotalHour = findView(R.id.tv_task_time_total_hour);
        tvTimeTotalMin = findView(R.id.tv_task_time_total_minute);
        tvTimeTotalSecond = findView(R.id.tv_task_time_total_second);
        tvTimeCoin = findView(R.id.tv_task_time_coin);
        tvNowTime = findView(R.id.tv_task_today_now_time);
        tvTodayServiceTime = findView(R.id.tv_task_today_service_time);
        tvTimeMarker = findView(R.id.tv_task_time_marker);
        tvUserManage = findView(R.id.tv_task_user_manager);
        tvRanking = findView(R.id.tv_task_service_ranking);
        tvClockIn = findView(R.id.tv_task_clock_record);
        tvHonor = findView(R.id.tv_task_honor);
//        mBanner = findView(R.id.task_banner);
        rvBanner = findView(R.id.rv_task_banner);
        llClockIn = findView(R.id.ll_clock_in);
        llVolunteer = findView(R.id.ll_volunteer_act);
        rvClockIn = findView(R.id.rv_clock_in);
        rvVolunteer = findView(R.id.rv_volunteer_act);
        tvLookMore = findView(R.id.tv_task_look_more);

        ivMsg.setOnClickListener(this);
        tvTimeMarker.setOnClickListener(this);
        tvUserManage.setOnClickListener(this);
        tvRanking.setOnClickListener(this);
        tvClockIn.setOnClickListener(this);
        tvHonor.setOnClickListener(this);
        tvLookMore.setOnClickListener(this);
    }

    private void initRv() {
        LinearLayoutManager bannerLm = new LinearLayoutManager(mContext);
        bannerLm.setOrientation(LinearLayoutManager.VERTICAL);
        rvBanner.setItemAnimator(new DefaultItemAnimator());
        bannerLm.setOrientation(LinearLayoutManager.VERTICAL);
        rvBanner.setNestedScrollingEnabled(false);
        rvBanner.setLayoutManager(bannerLm);
        rvBanner.setHasFixedSize(true);

        LinearLayoutManager lm1 = new LinearLayoutManager(mContext);
        lm1.setOrientation(LinearLayoutManager.VERTICAL);
        rvClockIn.setItemAnimator(new DefaultItemAnimator());
        lm1.setOrientation(LinearLayoutManager.VERTICAL);
        rvClockIn.setLayoutManager(lm1);
        rvClockIn.setHasFixedSize(true);

        LinearLayoutManager lm2 = new LinearLayoutManager(mContext);
        lm2.setOrientation(LinearLayoutManager.VERTICAL);
        rvVolunteer.setItemAnimator(new DefaultItemAnimator());
        lm1.setOrientation(LinearLayoutManager.VERTICAL);
        rvVolunteer.setLayoutManager(lm2);
        rvVolunteer.setHasFixedSize(true);
    }

    private void initRequest() {
        taskRequest = new TaskRequest(mContext);
        taskRequest.setmListener(new TaskDataListener() {
            @Override
            public void onSucceed(int what, String code, Object object) {

                if (object instanceof TaskData) {
                    TaskData result = (TaskData) object;

                    switch (what) {

                        case TaskRequest.HOME_DATA_WHAT:
                            mTaskData.setTimeService(result.getTimeService());
                            mTaskData.setTimeCoin(result.getTimeCoin());
                            mTaskData.setTodayActTotalTime(result.getTodayActTotalTime());
                            mTaskData.setNowTime(result.getNowTime());
                            mTaskData.setLoginAwardTimeCoins(result.getLoginAwardTimeCoins());
                            mTaskData.setEndTime(result.getEndTime());
                            mTaskData.setUnReadMsgNotify(result.getUnReadMsgNotify());
                            bindHeaders();
                            break;

                        case TaskRequest.HOME_BANNER_LIST_WHAT:
                            mTaskData.setBanners((result.getBanners()));
                            initBanner();
                            break;

                        case TaskRequest.HOME_DATA_LIST_WHAT:
                            mTaskData.setNowTime(result.getNowTime());
                            mTaskData.setRecentActArrays(result.getRecentActArrays());
                            for (TaskData.ClockInArray clock : result.getClockInArrays()) {
                                clock.setLocation(curLocation);
                            }
                            mTaskData.setClockInArrays(result.getClockInArrays());
                            setClockAdapter();
                            setRecentAdapter();
                            break;

                        default:
                            break;
                    }

                } else {
                    ClockOn clockOn = (ClockOn) object;
                    if (TextUtils.equals(code, "10001")) {
                        switch (what) {
                            case TaskRequest.CLOCK_ON_USER_START:
                                ToastUtils.showShort("开始活动成功");
                                taskRequest.getTaskDataList();
                                break;

                            case TaskRequest.CLOCK_ON_USER_END:
                                // 活动结束成功页
                                ClockScActivity.start(mContext, clockOn);
                                break;

                            default:
                                break;
                        }
                    } else {
                        // 其他异常
                        return;
                    }
                }
            }
        });
        taskRequest.getTaskData();
        taskRequest.getTaskBanners();
        taskRequest.getTaskDataList();
    }

    private void bindRegAward() {
        String regAward = mContext.getIntent().getStringExtra(MainActivity.EXTRA_REGISTER_AWARD);
        if (!TextUtils.isEmpty(regAward)) {
            float coin = Float.parseFloat(regAward);
            if (coin > 0) {
                if (welBackPW == null || !welBackPW.isShowing()) {
                    launchBack(regAward, true);
                }
            }
        }
    }

    private void bindHeaders() {
        tvTimeLev.setText(new StringBuilder().append("LV.").append(userViewModel.getTimeLev()));
        tvVipLev.setText(new StringBuilder().append("VIP").append(userViewModel.getVipLev()));
        if (TextUtils.equals(application.getString(R.string.zero), mTaskData.getUnReadMsgNotify())) {
            ivMsg.setImageResource(R.drawable.iv_message_normal);
        } else {
            ivMsg.setImageResource(R.drawable.iv_message_has);
        }

        if (!TextUtils.equals("0", userViewModel.getVipLev())) {
            ivLayer.setVisibility(View.VISIBLE);
        } else {
            ivLayer.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mTaskData.getTimeService())
                && !TextUtils.equals(mTaskData.getTimeService(), application.getString(R.string.zero))) {
            long distanceTimes = Long.parseLong(mTaskData.getTimeService());
            int[] format = TimeUtils.formatTimeArray(distanceTimes);
            if (format.length > 2) {
                // 00:00:00
                if (String.valueOf(format[0]).length() == 1) {
                    tvTimeTotalHour.setText(new StringBuffer().append("0").append(format[0]).append(""));
                } else {
                    tvTimeTotalHour.setText(new StringBuffer().append(format[0]).append(""));
                }

                if (String.valueOf(format[1]).length() == 1) {
                    tvTimeTotalMin.setText(new StringBuffer().append("0").append(format[1]).append(""));
                } else {
                    tvTimeTotalMin.setText(new StringBuffer().append(format[1]).append(""));
                }
                if (String.valueOf(format[2]).length() == 1) {
                    tvTimeTotalSecond.setText(new StringBuffer().append("0").append(format[2]).append(""));
                } else {
                    tvTimeTotalSecond.setText(new StringBuffer().append(format[2]).append(""));
                }
            } else if (format.length > 1) {
                tvTimeTotalHour.setText(getString(R.string.double_zero));

                if (String.valueOf(format[0]).length() == 1) {
                    tvTimeTotalMin.setText(new StringBuffer().append("0").append(format[0]).append(""));
                } else {
                    tvTimeTotalMin.setText(new StringBuffer().append(format[0]).append(""));
                }
                if (String.valueOf(format[1]).length() == 1) {
                    tvTimeTotalSecond.setText(new StringBuffer().append("0").append(format[1]).append(""));
                } else {
                    tvTimeTotalSecond.setText(new StringBuffer().append(format[1]).append(""));
                }
            } else {
                tvTimeTotalHour.setText(getString(R.string.double_zero));
                tvTimeTotalMin.setText(getString(R.string.double_zero));
                tvTimeTotalSecond.setText(getString(R.string.double_zero));
            }
        } else {
            tvTimeTotalHour.setText(getString(R.string.double_zero));
            tvTimeTotalMin.setText(getString(R.string.double_zero));
            tvTimeTotalSecond.setText(getString(R.string.double_zero));
        }

        tvTimeCoin.setText(mTaskData.getTimeCoin());

        if (!TextUtils.isEmpty(mTaskData.getLoginAwardTimeCoins())) {
            float coin = Float.parseFloat(mTaskData.getLoginAwardTimeCoins());
            if (coin > 0) {
                if (welBackPW == null || !welBackPW.isShowing()) {
                    launchBack(mTaskData.getLoginAwardTimeCoins(), false);
                }
            }
        }

        String maxTime;
        String nowTime = mTaskData.getNowTime();
        if (nowTime.length() > 10) {
            String[] split = nowTime.split(" ");
            maxTime = new StringBuilder().append(split[0]).append(" 23:59:59").toString();
            nowTimeCountDown = TimeUtils.getDisTimes(nowTime, maxTime);
            nowTimeCountDown();
            timer.schedule(task, 1000, 1000);
        }

        // 计时累积公益时间
        if (!TextUtils.equals(application.getString(R.string.zero), mTaskData.getEndTime())
                && TimeUtils.compareTime(mTaskData.getNowTime(), mTaskData.getEndTime())) {
            String todayActTotalTime = mTaskData.getTodayActTotalTime();
            todayServiceTime = Long.parseLong(todayActTotalTime);
            serviceTimeCountDown();
            serviceTimer.schedule(serviceTimeTask, 1000, 1000);
        }
    }


    private void nowTimeCountDown() {
        String showTime = TimeUtils.formatTimeMh(nowTimeCountDown);
        tvNowTime.setText(showTime);
    }

    private void serviceTimeCountDown() {
        String showTime = TimeUtils.formatTimeXx(todayServiceTime);
        tvTodayServiceTime.setText(showTime);
    }


    private void launchBack(String coin, boolean isRegister) {
        final Window window = mContext.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        welBackPW = new WelBackPW(mContext, llParent);
        welBackPW.setRegister(isRegister);
        welBackPW.setTimeCoin(coin);
        welBackPW.showAtLocation(llParent, Gravity.CENTER, 0, 0);
        welBackPW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void initBanner() {
        final List<AppBanner> banners = mTaskData.getBanners();
        if (banners.isEmpty()) {
            return;
        }

        /*bannerImages.clear();
        for (AppBanner banner : banners) {
            bannerImages.add(banner.getPicUrl());
        }

        if (bannerImages.size() > 1) {
            mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            mBanner.setIndicatorGravity(BannerConfig.CENTER);
            mBanner.isAutoPlay(true);
        } else {
            mBanner.setIndicatorGravity(BannerConfig.NOT_INDICATOR);
            mBanner.setViewPagerIsScroll(false);
            mBanner.isAutoPlay(false);
        }
        mBanner.setImages(bannerImages).setImageLoader(new GlideImageLoader()).start();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                AppBanner banner = banners.get(position);
                if (TextUtils.equals(banner.getActiveState(), application.getString(R.string.one))) {
                    WebDetailActivity.start(mContext, getString(R.string.app_banner), banner.getActiveUrl());
                }
            }
        });*/

        if (mBannerAdapter == null) {
            mBannerAdapter = new BannerAdapter(mContext, banners, 1);
            mBannerAdapter.setOnItemClickListener(new BaseRecAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o) {
                    if (o instanceof AppBanner) {
                        AppBanner banner = (AppBanner) o;
                        if (TextUtils.equals(banner.getActiveState(), application.getString(R.string.one))) {
                            String url = banner.getActiveUrl();
                            WebDetailActivity.start(mContext,
                                    application.getString(R.string.app_banner),
                                    url);
                        }
                    }

                }
            });
            rvBanner.setAdapter(mBannerAdapter);
        } else {
            mBannerAdapter.updateData(banners);
        }

    }

    private void setRecentAdapter() {
        if (mTaskData.getRecentActArrays().isEmpty()) {
            llVolunteer.setVisibility(View.GONE);
        } else {
            llVolunteer.setVisibility(View.VISIBLE);
        }

        if (mRecentAdapter == null) {
            mRecentAdapter = new RecentAdapter(mContext, mTaskData.getRecentActArrays(), 1);
            mRecentAdapter.setOnItemClickListener(new BaseRecAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o) {
                    if (o instanceof TaskData.RecentActArray) {
                        String url = new StringBuilder()
                                .append(DiscoveryFragment.detailUrl)
                                .append(((TaskData.RecentActArray) o).getId())
                                .toString();
                        WebDetailActivity.start(mContext,
                                application.getString(R.string.volunteer_flag),
                                url);
                    }

                }
            });
            rvVolunteer.setAdapter(mRecentAdapter);
        } else {
            mRecentAdapter.updateData(mTaskData.getRecentActArrays());
        }
    }

    private void setClockAdapter() {
        if (mTaskData.getClockInArrays().isEmpty()) {
            llClockIn.setVisibility(View.GONE);
        } else {
            llClockIn.setVisibility(View.VISIBLE);
        }
        if (mClockAdapter == null) {
            mClockAdapter = new ClockAdapter(mContext, mTaskData.getClockInArrays(), 1);
            mClockAdapter.setNowTime(mTaskData.getNowTime());
            mClockAdapter.setOnItemClickListener(new BaseRecAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o) {
                    if (o instanceof TaskData.ClockInArray) {
                        TaskData.ClockInArray clock = (TaskData.ClockInArray) o;
                        switch (view.getId()) {

                            case R.id.ll_clock_item_parent:
                                String url = new StringBuilder()
                                        .append(DiscoveryFragment.detailUrl)
                                        .append(clock.getId())
                                        .toString();
                                WebDetailActivity.start(mContext,
                                        application.getString(R.string.volunteer_flag),
                                        url);
                                break;

                            case R.id.tv_clock_down:
                                // 改变选中的地点
                                curPosition = position;
                                TimeMapActivity.start(
                                        TaskFragment.this,
                                        TIME_MAP_REQUEST_CODE,
                                        getString(R.string.map_flag_apply),
                                        clock.getLocation());
                                break;

                            case R.id.tv_clock_button:
                                if (TextUtils.equals("canStartAct", clock.getType())) {
                                    // 开始活动
                                    if (aMapLocation != null) {
                                        taskRequest.startAct(clock.getActChildId(), aMapLocation);
                                    } else {
                                        ToastUtils.showShort("获取位置信息失败");
                                    }

                                } else if (TextUtils.equals("canEndAct", clock.getType())) {
                                    // 结束活动

                                    taskRequest.clockOnCompanyEnd(
                                            clock.getActChildId());
                                } else {
                                    return;
                                }
                                break;

                            default:
                                break;
                        }

                    }

                }
            });
            rvClockIn.setAdapter(mClockAdapter);
        } else {
            mClockAdapter.updateData(mTaskData.getClockInArrays());
        }
    }

    @Override
    public int bindLayoutId() {
        return R.layout.fragment_task;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.tv_task_time_lev:
                break;

            case R.id.tv_task_vip_lev:
                String vipUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/member-level/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android-back")
                        .toString();
                WebDetailActivity.start(mContext, getString(R.string.task_vip_level), vipUrl);
                break;

            case R.id.iv_task_message:
                String msgUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/message-center/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android-back")
                        .toString();
                WebDetailActivity.start(mContext, getString(R.string.task_msg_center), msgUrl);
                break;

            case R.id.tv_task_time_marker:
                // 时间商城
                startActivity(new Intent(mContext, YouZanMarkerActivity.class));
                break;

            case R.id.tv_task_user_manager:
                // 用户管理
                String url = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/user-manage/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android")
                        .toString();
                WebDetailActivity.start(mContext, getString(R.string.task_time_marker), url);
                break;

            case R.id.tv_task_service_ranking:
                // 公益排行
                String rankUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/public-welfare-ranking/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android")
                        .toString();
                WebDetailActivity.start(mContext, getString(R.string.task_service_ranking), rankUrl);
                break;

            case R.id.tv_task_clock_record:
                // 打卡记录
                String clockUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/punch-record/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android")
                        .toString();
                WebDetailActivity.start(mContext, getString(R.string.task_clock_record), clockUrl);
                break;

            case R.id.tv_task_honor:
                // 荣誉
                String honorUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/honor/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .toString();
                WebDetailActivity.start(mContext, getString(R.string.task_honor), honorUrl);
                break;

            case R.id.tv_task_look_more:
                EventBus.getDefault().post(new BaseEvent(application.getString(R.string.tab_discovery_title)));
                break;

            default:
                break;

        }
    }

    private void andPermission() {
        // 需要调用AndPermission来开启定位权限提示
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 100) {
                // 表示定位的权限申请通过
                createLocationRequest();
            }

        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == 100) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort("请开启你的定位权限");
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(mContext, 404).show();

            }

        }
    };

    protected void createLocationRequest() {

        // 初始化请求
        locationRequest = new AMapLocationClient(mContext.getApplicationContext());

        // 设置回调监听
        locationRequest.setLocationListener(this);

        // 初始化参数集
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        // 高精度定位模式，省电模式， 仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        // 是否返回地址信息
        mLocationOption.setNeedAddress(true);

        // 设置重定位时间间隔
        mLocationOption.setInterval(5000);

        mLocationOption.setOnceLocation(true);

        // 设置参数集
        locationRequest.setLocationOption(mLocationOption);

        locationRequest.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            ToastUtils.showShort("定位失败");
            return;
        }

        Logger.i("Current user postion is lat : " + aMapLocation.getLatitude() +
                " and lon : " + aMapLocation.getLongitude());
        this.aMapLocation = aMapLocation;
        curLocation = aMapLocation.getAddress();
        for (TaskData.ClockInArray clock : mTaskData.getClockInArrays()) {
            clock.setLocation(curLocation);
        }
        setClockAdapter();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case 404:
                // 用户从设置中回来，无论有没有开启所需要的权限
//                ToastUtils.showShort("从设置中回来");
                break;

            case TIME_MAP_REQUEST_CODE:
                if (null != data) {
                    String location = data.getStringExtra(Constant.LOCATION);

                    if (!TextUtils.isEmpty(location)) {
                        // 更新数据
                        mTaskData.getClockInArrays().get(curPosition).setLocation(location);
                        setClockAdapter();
                    }
                }
                break;

            default:
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(BaseEvent event) {
        if (TextUtils.isEmpty(event.getBaseType())) {
            return;
        }
        if (TextUtils.equals(event.getBaseType(), getString(R.string.refresh_task_fragment_data))) {
            taskRequest.getTaskDataList();
        }
    }

    private MyHandler handler = new MyHandler(this);

    private static class MyHandler extends Handler {

        private final WeakReference<TaskFragment> mTaskFragment;

        private MyHandler(TaskFragment taskFragment) {
            this.mTaskFragment = new WeakReference<>(taskFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            TaskFragment mInstance = mTaskFragment.get();
            if (mInstance == null){
                return;
            }
            switch (msg.what) {
                case 1:
                    mInstance.nowTimeCountDown-=1000;
                    mInstance.updateNowTime();
                    break;

                case 2:
                    mInstance.todayServiceTime+=1000;
                    mInstance.updateServiceTime();
                    break;

                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }

    void updateNowTime() {
        //刷新当前时间倒计时
        nowTimeCountDown();
    }

    private void updateServiceTime() {
        //刷新公益时间计时器
        serviceTimeCountDown();
    }

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };

    Timer serviceTimer = new Timer();
    TimerTask serviceTimeTask = new TimerTask() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 2;
            handler.sendMessage(message);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if (null != welBackPW) {
            welBackPW.dismiss();
            welBackPW = null;
        }

        if (null != timer) {
            timer.cancel();
            timer = null;
        }

        if (null != serviceTimer) {
            serviceTimer.cancel();
            serviceTimer = null;
        }

        if (null != handler){
            handler.removeCallbacksAndMessages(null);
        }
    }
}
